package com.zhou.jvm.loading.testtwo;

import com.zhou.jvm.loading.testone.HelloWorld;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

/**
 * @author zhouyanxiang
 * @createTime 2020-07-2020/7/27-8:41
 */
public class OverrideClassLoad  extends ClassLoader{

    @Override
    public Class<?> findClass(String name) throws ClassNotFoundException{
        String path = "D:\\WorkSpace\\IdeaWorkSpace";
        File file = new File(path,name.replace(".","/"));
        try {
            // 输入输出流读取文件
            FileInputStream fis = new FileInputStream(file);
            ByteArrayOutputStream buf = new ByteArrayOutputStream();
            int b = 0;
            while ((b = fis.read())!=0){
                buf.write(b);
            }
            byte[] bytes = buf.toByteArray();
            // 关流
            buf.close();
            fis.close();
            return defineClass(name,bytes,0,bytes.length);
        } catch (IOException e) {
            e.printStackTrace();

        }
        return  super.findClass(name);
    }


    public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException {
        ClassLoader c1 = new OverrideClassLoad();
        Class aClass = c1.loadClass("com.zhou.jvm.loading.testone.HelloWorld");
        Class aClass2 = c1.loadClass("com.zhou.jvm.loading.testone.HelloWorld");
        System.out.println(aClass == aClass2);

        HelloWorld helloWorld = (HelloWorld) aClass.newInstance();
        helloWorld.method();

        System.out.println(c1.getClass().getClassLoader());
        System.out.println(c1.getClass());
        System.out.println(c1.getParent());
    }
}
